<template>
  <div class="erp-layout">
    <!-- 顶部导航栏 -->
    <div class="erp-header">
      <div class="header-left">
        <h1>斯凡供应链</h1>
      </div>
      <!-- 用户信息 -->
      <div class="header-right">
        <div v-if="userStore.token" class="user-dropdown">
          <t-dropdown trigger="click" :options="userMenuOptions" @click="handleUserMenuClick">
            <div class="user-info-trigger">
              <t-avatar size="32px" :image="userStore.userInfo?.avatar">
                {{ (userStore.userInfo?.nickname || userStore.userInfo?.username || 'U')?.charAt(0)?.toUpperCase() }}
              </t-avatar>
              <div class="user-details">
                <div class="user-name">{{ userStore.userInfo?.nickname || userStore.userInfo?.username || '用户' }}</div>
                <div class="user-role">{{ userStore.userInfo?.role || '管理员' }}</div>
              </div>
              <component :is="'ChevronDownIcon'" size="16" />
            </div>
          </t-dropdown>
        </div>
        <div v-else class="login-section">
          <t-button theme="primary" @click="router.push('/login')">登录</t-button>
        </div>
      </div>
    </div>

    <!-- 主体内容区域 -->
    <div class="erp-body">
      <!-- 左侧菜单栏 -->
      <div class="erp-sidebar">
        <t-menu 
          v-model:value="activeMenu" 
          :collapsed="false"
          theme="light"
          width="240px"
        >
          <!-- 首页菜单项 -->
          <t-menu-item value="dashboard" @click="router.push('/dashboard')">
            <template #icon><component :is="'HomeIcon'" /></template>
            首页
          </t-menu-item>
          
          <!-- 动态菜单项 -->
          <template v-for="menu in menuData" :key="menu.value">
            <t-submenu :value="menu.value" :title="menu.title">
              <template #icon><component :is="menu.icon" /></template>
              <t-menu-item 
                v-for="item in menu.children" 
                :key="item.value" 
                :value="item.value"
                @click="handleMenuClick(item)"
              >
                {{ item.title }}
              </t-menu-item>
          </t-submenu>
          </template>
        </t-menu>
      </div>

      <!-- 主内容区域 -->
      <div class="erp-main">
        <div class="main-content">
          <slot></slot>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, h, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { MessagePlugin } from 'tdesign-vue-next'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 调试用户状态
onMounted(() => {
  console.log('ErpLayout mounted - 用户状态:', {
    token: userStore.token,
    userInfo: userStore.userInfo,
    hasUsername: !!userStore.userInfo?.username
  })
})

// 当前激活的菜单项
const activeMenu = ref('dashboard')

// 菜单数据
const menuData = ref([
  {
    value: 'system',
    title: '系统业务',
    icon: 'SettingIcon',
    children: [
      { value: 'UserIcon', title: '用户管理', path: '/system/users' },
      { value: 'role-management', title: '角色管理', path: '/system/roles' },
      { value: 'permission-management', title: '权限管理', path: '/system/permissions' },
      { value: 'organization', title: '组织架构', path: '/system/organization' }
    ]
  },
  {
    value: 'operations',
    title: '运营管理',
    icon: 'ShopIcon',
    children: [
      { value: 'product-management', title: '商品管理', path: '/operations/products' },
      { value: 'inventory-management', title: '库存管理', path: '/operations/inventory' },
      { value: 'order-management', title: '订单管理', path: '/operations/orders' },
      { value: 'customer-management', title: '客户管理', path: '/operations/customers' }
    ]
  },
  {
    value: 'technical',
    title: '技术支持',
    icon: 'SystemComponentsIcon',
    children: [
      { value: 'system-monitoring', title: '系统监控', path: '/technical/monitoring' },
      { value: 'log-management', title: '日志管理', path: '/technical/logs' },
      { value: 'backup-restore', title: '备份恢复', path: '/technical/backup' },
      { value: 'api-documentation', title: 'API文档', path: '/technical/api-docs' }
    ]
  },
  {
    value: 'ledger',
    title: '台账管理',
    icon: 'LeaderboardIcon',
    children: [
      { value: 'financial-ledger', title: '财务台账', path: '/ledger/financial' },
      { value: 'inventory-ledger', title: '库存台账', path: '/ledger/inventory' },
      { value: 'sales-ledger', title: '销售台账', path: '/ledger/sales' },
      { value: 'purchase-ledger', title: '采购台账', path: '/ledger/purchase' }
    ]
  },
  {
    value: 'control',
    title: '控制中心',
    icon: 'ControlPlatformIcon',
    children: [
      { value: 'workflow-control', title: '流程控制', path: '/control/workflow' },
      { value: 'approval-center', title: '审批中心', path: '/control/approval' },
      { value: 'notification-center', title: '消息中心', path: '/control/notifications' },
      { value: 'task-center', title: '任务中心', path: '/control/tasks' }
    ]
  },
  {
    value: 'production',
    title: '生产管理',
    icon: 'PreciseMonitorIcon',
    children: [
      { value: 'production-plan', title: '生产计划', path: '/production/plan' },
      { value: 'production-order', title: '生产订单', path: '/production/orders' },
      { value: 'quality-control', title: '质量控制', path: '/production/quality' },
      { value: 'equipment-management', title: '设备管理', path: '/production/equipment' }
    ]
  },
  {
    value: 'finance',
    title: '财务管理',
    icon: 'WalletIcon',
    children: [
      { value: 'financial-overview', title: '财务总览', path: '/finance/overview' },
      { value: 'accounts-receivable', title: '应收账款', path: '/finance/receivable' },
      { value: 'accounts-payable', title: '应付账款', path: '/finance/payable' },
      { value: 'cost-analysis', title: '成本分析', path: '/finance/cost-analysis' }
    ]
  },
  {
    value: 'development',
    title: '开发工具',
    icon: 'SystemComponentsIcon',
    children: [
      { value: 'test-mock', title: 'Mock测试', path: '/test-mock' },
      { value: 'test-icons', title: '图标测试', path: '/test-icons' }
    ]
  }
])

// 用户菜单选项
const userMenuOptions = ref([
  {
    content: '个人信息',
    value: 'profile',
    prefixIcon: () => h('t-icon', { name: 'user' })
  },
  {
    content: '修改密码',
    value: 'changePassword',
    prefixIcon: () => h('t-icon', { name: 'lock-on' })
  },
  {
    content: '系统设置',
    value: 'settings',
    prefixIcon: () => h('t-icon', { name: 'setting' })
  },
  {
    content: '退出登录',
    value: 'logout',
    prefixIcon: () => h('t-icon', { name: 'logout' }),
    theme: 'error'
  }
])

// 处理菜单点击
const handleMenuClick = (item) => {
  if (item.path) {
    router.push(item.path)
  } else {
    MessagePlugin.info(`${item.title}功能开发中...`)
  }
}

// 处理用户菜单点击
const handleUserMenuClick = async (data) => {
  switch (data.value) {
    case 'profile':
      router.push('/profile')
      break
    case 'changePassword':
      MessagePlugin.info('修改密码功能开发中...')
      break
    case 'settings':
      MessagePlugin.info('系统设置功能开发中...')
      break
    case 'logout':
      await handleLogout()
      break
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await userStore.logout()
    MessagePlugin.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    MessagePlugin.error('退出登录失败')
  }
}

// 根据当前路由设置激活菜单
const updateActiveMenu = () => {
  const path = route.path
  if (path === '/dashboard') {
    activeMenu.value = 'dashboard'
  } else if (path === '/profile') {
    activeMenu.value = 'profile'
  }
  // 可以根据需要添加更多路由映射
}

// 监听路由变化
router.afterEach(() => {
  updateActiveMenu()
})

// 初始化激活菜单
updateActiveMenu()
</script>

<style scoped>
.erp-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部导航栏 */
.erp-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
  padding: 0 24px;
  background: white;
  border-bottom: 1px solid #e7e7e7;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  z-index: 1000;
}

.header-left h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.header-right {
  display: flex;
  align-items: center;
}

/* 用户下拉菜单 */
.user-dropdown {
  position: relative;
}

.user-info-trigger {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-info-trigger:hover {
  background-color: #f3f4f6;
}

.user-details {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  line-height: 1.2;
}

.user-role {
  font-size: 12px;
  color: #6b7280;
  line-height: 1.2;
}

/* 主体区域 */
.erp-body {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧菜单栏 */
.erp-sidebar {
  width: 240px;
  background: white;
  border-right: 1px solid #e7e7e7;
  overflow-y: auto;
}

/* 主内容区域 */
.erp-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

/* 登录按钮区域 */
.login-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .erp-sidebar {
    width: 200px;
  }
  
  .erp-header {
    padding: 0 16px;
  }
  
  .header-left h1 {
    font-size: 18px;
  }
  
  .user-details {
    display: none;
  }
}

@media (max-width: 640px) {
  .erp-body {
    flex-direction: column;
  }
  
  .erp-sidebar {
    width: 100%;
    height: auto;
    max-height: 200px;
  }
  
  .main-content {
    padding: 16px;
  }
}
</style>
